// React核心库导入
import React, { useEffect, useMemo } from 'react';
// Ant Design组件库导入
import { 
  Table,      // 表格组件
  Button,     // 按钮组件
  Space,      // 间距组件
  Tag,        // 标签组件
  Card,       // 卡片组件
  Input,      // 输入框组件
  Select,     // 选择器组件
  Badge,      // 徽章组件
  Tooltip,    // 工具提示组件
  message,    // 消息提示组件
  Popconfirm, // 确认对话框组件
  Dropdown,   // 下拉菜单组件
  Menu        // 菜单组件
} from 'antd';
// Ant Design表格类型导入
import type { ColumnsType } from 'antd/es/table';
// Ant Design图标库导入
import { 
  PlusOutlined,        // 加号图标
  EditOutlined,        // 编辑图标
  DeleteOutlined,      // 删除图标
  ReloadOutlined,      // 刷新图标
  SearchOutlined,      // 搜索图标
  EyeOutlined,         // 查看图标
  MessageOutlined,     // 消息图标
  CheckCircleOutlined, // 成功图标
  CloseCircleOutlined, // 失败图标
  MoreOutlined,        // 更多图标
  StopOutlined,        // 停止图标
  RedoOutlined         // 重做图标
} from '@ant-design/icons';
// React Router路由组件导入
import { Link } from 'react-router-dom';
// 状态管理Hook导入
import { useConversation, useConversationLoading, useConversationError, useConversationFilters, useConversations } from '@contexts/ConversationContext';
// 服务层导入
import conversationService, { ConversationStatus } from '@services/conversationService';

// 解构组件
const { Search } = Input;
const { Option } = Select;
const { Group: ButtonGroup } = Button;

/**
 * 对话列表组件 - 对话管理主页面
 * 
 * 功能特性：
 * - 对话数据列表展示和分页
 * - 多条件搜索和过滤功能
 * - 对话状态管理操作
 * - 批量操作支持
 * - 实时状态监控
 * - 响应式设计支持
 * 
 * @author CKY Agent Platform Team
 * @version 2.0.0
 * @lastModified 2024-01-20
 */
const ConversationList: React.FC = () => {
  // 使用状态管理Hook
  const { state, actions } = useConversation();
  const loading = useConversationLoading();
  const error = useConversationError();
  const { filters, setFilters, resetFilters } = useConversationFilters();
  const conversations = useConversations();

  // 状态显示映射
  const statusMap = conversationService.conversationStatusMap;

  // 处理搜索
  const handleSearch = (value: string) => {
    setFilters({ filter: value, skipCount: 0 });
  };

  // 处理状态过滤
  const handleStatusFilter = (value: ConversationStatus | undefined) => {
    setFilters({ status: value, skipCount: 0 });
  };

  // 处理激活状态过滤
  const handleActiveFilter = (value: boolean | undefined) => {
    setFilters({ isActive: value, skipCount: 0 });
  };

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setFilters({
      skipCount: (pagination.current - 1) * pagination.pageSize,
      maxResultCount: pagination.pageSize
    });
  };

  // 删除对话
  const handleDelete = async (id: string) => {
    try {
      await actions.deleteConversation(id);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 关闭对话
  const handleClose = async (id: string) => {
    try {
      await actions.closeConversation(id);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 重新打开对话
  const handleReopen = async (id: string) => {
    try {
      await actions.reopenConversation(id);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    actions.fetchConversations();
    actions.fetchStatistics();
  };

  // 重置过滤器
  const handleResetFilters = () => {
    resetFilters();
  };

  // 表格列定义
  const columns: ColumnsType<any> = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: any) => (
        <Link to={`/conversations/${record.id}`} style={{ fontWeight: 'bold' }}>
          {text}
        </Link>
      ),
      sorter: true,
      width: 200
    },
    {
      title: '智能体',
      dataIndex: 'agentName',
      key: 'agentName',
      render: (text: string, record: any) => (
        <Tag color="blue">
          {text || '未知智能体'}
        </Tag>
      ),
      width: 150
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      width: 250
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: ConversationStatus) => {
        const statusInfo = statusMap[status];
        return (
          <Badge 
            status={statusInfo.color as any} 
            text={statusInfo.text}
            style={{ display: 'flex', alignItems: 'center' }}
          />
        );
      },
      filters: Object.entries(statusMap).map(([value, statusInfo]: [string, any]) => ({
        text: statusInfo.text,
        value: value
      })),
      width: 120
    },
    {
      title: '消息数',
      dataIndex: 'messageCount',
      key: 'messageCount',
      render: (count: number) => (
        <Badge count={count} showZero color="#52c41a" />
      ),
      sorter: true,
      width: 100
    },
    {
      title: '激活状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'success' : 'default'}>
          {isActive ? '激活' : '停用'}
        </Tag>
      ),
      filters: [
        { text: '激活', value: true },
        { text: '停用', value: false }
      ],
      width: 100
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      render: (tags: string[]) => (
        <Space size="small" wrap>
          {tags?.slice(0, 3).map((tag, index) => (
            <Tag key={index} color="purple">
              {tag}
            </Tag>
          ))}
          {tags?.length > 3 && (
            <Tag color="purple">
              +{tags.length - 3}
            </Tag>
          )}
        </Space>
      ),
      width: 150
    },
    {
      title: '最后消息',
      dataIndex: 'lastMessageAt',
      key: 'lastMessageAt',
      render: (text: string) => text ? new Date(text).toLocaleString() : '-',
      sorter: true,
      width: 160
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString(),
      sorter: true,
      width: 160
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: any) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Link to={`/conversations/${record.id}`}>
              <Button icon={<EyeOutlined />} size="small" />
            </Link>
          </Tooltip>
          
          <Tooltip title="编辑">
            <Link to={`/conversations/${record.id}/edit`}>
              <Button icon={<EditOutlined />} size="small" />
            </Link>
          </Tooltip>

          <Dropdown
            menu={{
              items: [
                {
                  key: 'message',
                  label: '发送消息',
                  icon: <MessageOutlined />,
                  onClick: () => {
                    // 导航到对话详情页面
                    window.location.href = `/conversations/${record.id}`;
                  }
                },
                ...(record.status === ConversationStatus.Active ? [
                  {
                    key: 'close',
                    label: '关闭对话',
                    icon: <StopOutlined />,
                    onClick: () => handleClose(record.id)
                  }
                ] : [
                  {
                    key: 'reopen',
                    label: '重新打开',
                    icon: <RedoOutlined />,
                    onClick: () => handleReopen(record.id)
                  }
                ])
              ]
            }}
          >
            <Button icon={<MoreOutlined />} size="small" />
          </Dropdown>

          <Popconfirm
            title="确定要删除这个对话吗？删除后将无法恢复。"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button icon={<DeleteOutlined />} size="small" danger />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
      fixed: 'right',
      width: 180
    }
  ];

  // 计算分页配置
  const paginationConfig = {
    current: Math.floor((filters.skipCount || 0) / (filters.maxResultCount || 10)) + 1,
    pageSize: filters.maxResultCount || 10,
    total: state.totalCount,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => 
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100']
  };

  // 错误处理
  useEffect(() => {
    if (error) {
      message.error(error);
    }
  }, [error]);

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        {/* 页面标题和操作栏 */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold' }}>
              对话管理
            </h1>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                刷新
              </Button>
              <Link to="/conversations/create">
                <Button type="primary" icon={<PlusOutlined />}>
                  创建对话
                </Button>
              </Link>
            </Space>
          </div>
          
          {/* 搜索和过滤区域 */}
          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
            <Search
              placeholder="搜索对话标题或描述"
              style={{ width: 300 }}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
              allowClear
            />
            
            <Select
              placeholder="状态过滤"
              style={{ width: 120 }}
              allowClear
              onChange={handleStatusFilter}
            >
              {Object.entries(statusMap).map(([value, statusInfo]: [string, any]) => (
                <Option key={value} value={value}>
                  {statusInfo.text}
                </Option>
              ))}
            </Select>

            <Select
              placeholder="激活状态"
              style={{ width: 120 }}
              allowClear
              onChange={handleActiveFilter}
            >
              <Option value={true}>激活</Option>
              <Option value={false}>停用</Option>
            </Select>

            <Button onClick={handleResetFilters}>
              重置过滤
            </Button>
          </div>
        </div>

        {/* 数据统计信息 */}
        <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
          <Space size="large">
            <span>总对话数: <strong>{state.totalCount}</strong></span>
            <span>激活: <strong>{conversations.filter(c => c.isActive).length}</strong></span>
            <span>进行中: <strong>{conversations.filter(c => c.status === ConversationStatus.Active).length}</strong></span>
            <span>已关闭: <strong>{conversations.filter(c => c.status === ConversationStatus.Closed).length}</strong></span>
            <span>总消息: <strong>{conversations.reduce((sum, c) => sum + c.messageCount, 0)}</strong></span>
          </Space>
        </div>

        {/* 数据表格 */}
        <Table
          columns={columns}
          dataSource={conversations}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          onChange={handleTableChange}
          scroll={{ x: 1400 }}
          bordered
          size="middle"
        />
      </Card>
    </div>
  );
};

export default ConversationList;